package com.ly.consumer.redisson;

import com.common.redis.util.RedissonLockUtil;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
//redisson分布式锁
public class Redisson {


    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RedissonLockUtil redissonLockUtil;


    public String myRedissonLock(String key){
        //锁对象
        RLock lock = redissonClient.getLock(key);
        try {
            //上锁
            lock.lock();
            //todo 业务逻辑
        }catch (Exception e){
            //解锁
            lock.unlock();
        }finally {
            //解锁
            lock.unlock();
        }
        return "";
    }


    public void myRedissonLock(String key,long time){
        //设置redisson 分布式锁
        String lockKey = "likesRecordLock";
        // 尝试获取锁
        boolean isLockAcquired = redissonLockUtil.tryLock(lockKey, 10, 5);
        if (isLockAcquired) {
            try {
                //业务
            } catch (Exception e) {
                redissonLockUtil.unlock(lockKey);
                e.printStackTrace();
            } finally {
                // 释放锁
                redissonLockUtil.unlock(lockKey);
            }
        }
//        else{
        //这里是已经上锁了 可以返回前端做一些响应
//        }
    }
}
